import 'dart:convert';
import 'dart:io';

import 'package:jpush_flutter/jpush_flutter.dart';

class JmessageHelper {
  /// AppKey
  static String appKey = "d6010c51e331c74637b4bd6e";

  // 初始化
  static initPush() {
    // 初始化极光推送
    JPush().setup(
        appKey: appKey,
        production: false,
        channel: "developer-default",
        debug: true);
    // 申请推送权限
    JPush().applyPushAuthority(
        const NotificationSettingsIOS(badge: true, sound: true, alert: true));
    JPush().setAuth(enable: true);
  }

  /// 设置别名
  static setAlias(String alias) {
    return JPush().setAlias(alias);
  }

  /// 删除别名
  static Future<Map<dynamic, dynamic>> removeAlias() {
    return JPush().deleteAlias();
  }

  ///设置角标
  static Future setBadge(int badge) {
    return JPush().setBadge(badge);
  }

  /// 监听
  static addListenerEventHandler(
      {void Function(Map message)? receiveNotify,
      void Function(Map message)? onOpenNotify,
      void Function(Map message)? receiveCustomMessage,
      void Function(Map message)? onInAppMessageShow}) {
    JPush().addEventHandler(
        //接收通知回调方法。
        onReceiveNotification: (Map<String, dynamic> message) async {
          if (receiveNotify != null) {
            receiveNotify(message);
          }
        },
        // 点击通知回调方法。
        onOpenNotification: (Map<String, dynamic> message) async {
          if (onOpenNotify != null) {
            onOpenNotify(message);
          }
        },
        onInAppMessageShow: (Map<String, dynamic> message) async {
          if (onInAppMessageShow != null) {
            onInAppMessageShow(message);
          }
        },
        // 接收自定义消息回调方法。
        onReceiveMessage: (Map<String, dynamic> message) async {
          if (receiveCustomMessage != null) {
            receiveCustomMessage(message);
          }
        },
        onReceiveNotificationAuthorization:
            (Map<String, dynamic> message) async {});
  }

  static Map getExtras(message) {
    print("push mesagegegegegeg: ${message}");
    Map msg = {};
    if (Platform.isIOS) {
      msg = message['extras'];
    } else if (Platform.isAndroid) {
      msg = json.decode(message["extras"]["cn.jpush.android.EXTRA"]);
    }
    return msg;
  }
}
